package com.iwhalecloud.uncc.utils;

import com.iwhalecloud.uncc.common.SpringContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zq
 * @date 2021/10/21 14:17
 * @description BatchUtil
 */
@Slf4j
public class BatchUtil {

    private static JdbcTemplate jdbcTemplate;

    static {
        jdbcTemplate = (JdbcTemplate) SpringContext.getContext().getBean("jdbcTemplate");
    }
    /**
     *
     *
     * 批量插入 更新 删除
     * @param sql
     * @param beans
     * @return
     */
    public static int batchUpdateBeans(StringBuilder sql, List<?> beans) {
//        long s = System.currentTimeMillis();
//        log.info(Thread.currentThread().getName() + "执行SQL "+ sql.toString()+ DatasourceContextHolder.getDs()+"数据库 批量插入 更新 删除" );

        int[] results = null;
        try {
            SqlParameterSource[] params = SqlParameterSourceUtils.createBatch(beans.toArray());
            results = new NamedParameterJdbcTemplate(jdbcTemplate).batchUpdate(sql.toString(), params);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        log.info(Thread.currentThread().getName() +"执行SQL "+ sql.toString() + "耗时:"+ ((System.currentTimeMillis() - s) / 1000) + "s");
        if (results != null && results.length > 0) {
            return results.length;
        } else {
            return -1;
        }
    }

    /**
     * 批量查询
     * @param sql
     * @param beans
     * @param rowMapper
     * @return
     */
    public static List batchQueryBeans(StringBuilder sql, List<?> beans, RowMapper<?> rowMapper) {
//        long s = System.currentTimeMillis();
//        log.info(Thread.currentThread().getName() + "执行SQL "+ sql.toString() + DatasourceContextHolder.getDs()+"数据库 批量查询" );

        List results = new ArrayList();
        try {
            MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource();
            mapSqlParameterSource.addValue("i",beans);
            results = new NamedParameterJdbcTemplate(jdbcTemplate).query(sql.toString(), mapSqlParameterSource ,rowMapper);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
//        log.info(Thread.currentThread().getName() +"执行SQL "+ sql.toString() + "耗时:"+ ((System.currentTimeMillis() - s) / 1000) + "s");
        if (results != null && !results.isEmpty()) {
            return results;
        } else {
            return null;
        }
    }




}
